/**
* Copyright 2009 Waag Society <http://www.waag.org>
* This file is part of Annotrax.
*
* Annotrax is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Annotrax is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Annotrax.
* If not, see http://www.gnu.org/licenses/gpl.html
*/

/**
we load the form for annatating from the server
*/
self.AnnotationForm = function(container,movie,channel)
{
	this.el_main = Element("div",{className:"am_annotation_form"},container)
	this.form_url = ""
	this.movie = movie;
	this.channel = channel;
	this.annotation = null; //to be received on form get and submit
	this.form = null;
	
	this.start_time = null
	//this.stop_time = null
}
/**
We receive this on event 'player_progress' as long as we are in annotating form
*/
AnnotationForm.prototype.onPlayerProgress = function(evt,playlist_item,time_in_movie,time_in_fragment)
{
	time = time_in_movie
	if(this.start_time == null)
	{
		this.start_time = time;
	}
	duration = time-this.start_time;
	this.onSetDuration(evt,duration);
}
/**
set the form url to where we get the form adding new annnotations, listen to player progress event to set start and duration
*/
AnnotationForm.prototype.newAnnotation = function()
{
	this.start_time = null;
	this.duration = null;
		
	$(document).bind("player_progress.editor",bind(this,"onPlayerProgress")); //namespace bind only for this annotation edit form
	
	new_url =  "/annotation/add/" + this.movie.id + "/channel/"+ this.channel.id + "?format=json"; //we create a new annotation
	this.displayForm(new_url)
}
/**
set the form url to where we get the form editing existing annotations
*/
AnnotationForm.prototype.editAnnotation = function(annotation)
{
	new_url =  "/annotation/edit/" + annotation.id + "?format=json";
	this.start_time = annotation.time;
	this.duration = annotation.duration;
	
	this.displayForm(new_url)
}
/**
load the form, get it from the server encapsulated in json
*/
AnnotationForm.prototype.displayForm = function(url)
{
	$(document).trigger(jQuery.Event("annotation_start"));
	
	if((url != this.form_url) || $(this.el_main).html() == "")
	{
		this.annotation = null; //to be set by form get or post
		this.form_url = new_url;
		try
		{	
			$.ajax({
				type: "GET",
				url: this.form_url,
				dataType: "json",
				async:false,
				error: function(xmlhttp,error,what)
				{
					throw "error getting form"
				},
				success: bind(this,"onLoaded",[]) 
			});
		}
		catch(err)
		{
			throw "could not perform json request to get form, login first??, ik wil hier eigenlijk json";
		}
	}
}
/**
callback, gets called when the form was received from the server
*/
AnnotationForm.prototype.onLoaded = function(data)
{	
	
	if(data.success == true) //
	{
		$(this.el_main).html(data.form); //add form html  
		this.form = $("form",this.el_main)[0] //get form from dom
 		this.annotation = data.annotations[0];

		$(this.form).bind("submit",bind(this,"onSubmit"))
		
		if(this.annotation.id == null)
		{
			this.adaptFormNewAnnotation()
		}
		else
		{
			this.adaptFormExistingAnnotation()
		}
	}
	else
	{
		$(document).trigger(jQuery.Event("annotation_failed"),[])
		throw data.errors[0];
	}
}
/**
adapt the form for a new annotation, don't show spin buttons
*/
AnnotationForm.prototype.adaptFormNewAnnotation = function()
{
	$("input[type='submit']",this.form).hide()
	$(".startDuration",this.el_main).hide()
}
/**
adapt the form for an existing annotation, show the spinbuttons
*/
AnnotationForm.prototype.adaptFormExistingAnnotation = function()
{
	$(document).unbind("player_progress.editor"); //don't listen to player progress as annotation time setter
	$("input[type='submit']",this.form).hide()
	$(".input-start",this.el_main).atSpinButton().bind("spinbuttonchange", bind(this,"onSetStartTime") );
	$(".input-duration",this.el_main).atSpinButton().bind("spinbuttonchange", bind(this,"onSetDuration") );
}
/**
due to player progress or due to spinbuttons
*/
AnnotationForm.prototype.onSetStartTime = function(evt,val)
{
	this.start_time = val
	this.sendPreview()
}
/**
due to player progress or due to spinbuttons
*/
AnnotationForm.prototype.onSetDuration = function(evt,val)
{
	this.duration = val
	if(val < 1)
	{
		this.duration = 1
	}
	this.sendPreview()
}
/**

*/
AnnotationForm.prototype.cancel = function()
{
	$(document).unbind("player_progress.editor"); //don't listen anymore
	$(document).trigger(jQuery.Event("annotation_cancel"),[])
}
/**
possibly edited by player progress or manual by spin button
*/
AnnotationForm.prototype.sendPreview = function()
{	
	if(this.start_time != null) 
	{
		this.annotation.time = this.start_time;
	}
	if(this.duration != null)
	{
		this.annotation.duration = this.duration;		
	}
	//console.log(this.annotation)
	
	$(document).trigger(jQuery.Event("annotation_edit_preview"),[this.channel,this.annotation]);
}
/**

*/
AnnotationForm.prototype.beforeSubmit = function(formData, jqForm, options)
{

}
/**
disable form submit by original submit button or keypress
*/
AnnotationForm.prototype.onSubmit = function(evt)
{
	evt.preventDefault(); //
	return false; //IE way
}
/**
submit the form in the Ajax way, 
*/
AnnotationForm.prototype.submit2 = function(values)
{
	$(document).unbind("player_progress.editor"); //don't listen anymore
	
	if((this.start_time != null) && (this.duration != null))
	{
		//fill in the start and duration in the form to submit
		$(".input-start",this.form).val(this.start_time)
		$(".input-duration",this.form).val(this.duration)
		$(this.form).ajaxSubmit({ 
			beforeSubmit: bind(this,"beforeSubmit"), //args: formData, jqForm, options)
			success: bind(this,"onSubmitResponse",[]), //args: data, statusText 
			url: this.form_url,
			async: false, //send synchronized we want to return a result set by onSubmitResponse
			type: "POST",
			dataType: "json",
		});
	}
	else
	{
		throw "start / duration was not set"
	}
		
	return this.annotation;
}
/**
disable the original submit button
*/
AnnotationForm.prototype.onSubmitButtonClicked = function(form,evt)
{		
	stopAnnotation();
	evt.preventDefault(); //
	return false; //IE way
}
/**
on succes we should receive an array with one new or edited annotation, add or replace it in the (global) channels array
*/
AnnotationForm.prototype.onSubmitResponse = function(data, statusText)
{
	if(data.success == true) 
	{
		annotation = data.annotations[0]
		annotation.__proto__ = new Annotation() //extend the annotation obj with annotation prototype functions
		annotation.time = parseInt(annotation.time) //should not be necesairy (server send string)
		annotation.duration = parseInt(annotation.duration) //should not be necesairy
		annotation.channel = this.channel
		existing_annotation = this.channel.annotations.findObj("id",annotation.id);
		
		if(existing_annotation != null)
		{
			this.channel.annotations.remove(existing_annotation)
		}
	
		this.channel.annotations.push(annotation)
		this.annotation = annotation

		$(document).trigger(jQuery.Event("annotation_done"),[annotation,this.channel]);		
	}
	else
	{
		$(document).trigger(jQuery.Event("annotation_failed"),[])
		
		error_string = "" //we would like to get just a string instead of an object
		for(var se in data.errors)
		{
		 	if(data.errors[se] != "")
			{
				error_string += se
				error_string += "="
				error_string += data.errors[se]
			}
		}
		
		throw error_string;
	}
}